package com.sys.servlet.mgr.commodity;

import com.sys.entity.User;
import com.sys.exception.DuplicateCardException;
import com.sys.pojo.JsonResult;
import com.sys.service.CommodityService;
import com.sys.utils.WriteJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/mgr/commodity/add")
public class AddCommodityServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter writer = resp.getWriter();

        // 从session中获取当前登录人的信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        Integer uid = user.getUid();
//        cname,batch,expiretime,purchaseprice,price,inventory
        String cname = req.getParameter("cname");
        String batch = req.getParameter("batch");
        String expiretime = req.getParameter("expiretime");
        String purchaseprice = req.getParameter("purchaseprice");
        String price = req.getParameter("price");
        String inventory = req.getParameter("inventory");
        CommodityService service = new CommodityService();
        JsonResult jr = new JsonResult();
        try {
            //问题：如何获取当前登录用户的id
            service.add(cname,batch,expiretime,purchaseprice,price,inventory,uid);
            jr.setCode(0);
            jr.setMsg("添加成功！");
        } catch ( DuplicateCardException e){
            jr.setCode(104);
            jr.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            jr.setCode(500);
            jr.setMsg("操作发生错误！");
        }

        WriteJson.write(resp,jr);

    }
}
